<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <el-tab-pane label="角色管理">
            <!-- 左侧数据 -->
            <el-row style="height:60px">
              <el-button icon="el-icon-plus" type="primary" size="small" @click="showDialog=true">新增角色</el-button>
            </el-row>
            <!-- 给表格绑定数据 -->
            <el-table border="" :data="list">
              <el-table-column align="center" type="index" label="序号" width="120" />
              <el-table-column align="center" prop="name" label="名称" width="240" />
              <el-table-column align="center" prop="description" label="描述" />
              <el-table-column align="center" prop="" label="操作">

                <!-- 作用域插槽 -->
                <!-- row是当前点击行的数据 -->
                <template slot-scope="{ row }">
                  <el-button size="small" type="success" @click="assignPerm(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="editRole(row.id)">编辑</el-button>
                  <el-button size="small" type="danger" @click="delRole(row.id)">删除</el-button>
                </template>

              </el-table-column>
            </el-table>

            <!-- 分页器 -->
            <el-row type="flex" justify="center" align="middle" style="height:60px">
              <el-pagination layout="prev,pager,next" :total="page.total" :page-size="page.pagesize" :current-page="page.page" @current-change="changePage" />
            </el-row>

          </el-tab-pane>
          <el-tab-pane label="公司信息">
            <!-- 右侧数据 -->
            <!-- 不需要校验的表单无需model rules -->
            <el-alert type="info" :show-icon="true" :closable="false" title="请谨慎修改" />
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="企业名称">
                <el-input v-model="formData.name" style="width:400px" disabled />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="formData.companyAddress" style="width:400px" disabled />
              </el-form-item>
              <el-form-item label="电话">
                <el-input v-model="formData.companyPhone" style="width:400px" disabled />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="formData.mailbox" style="width:400px" disabled />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="formData.remarks" type="textarea" row="3" style="width:400px" disabled />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>

    </div>

    <!-- 放置一个弹层 -->
    <el-dialog title="新增/编辑部门" :visible="showDialog" @close="cancleBtn">
      <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
        <el-form-item prop="name" label="员工名称" style="width:85%">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="员工描述" style="width:85%">
          <el-input v-model="roleForm.description" />
        </el-form-item>
      </el-form>
      <!-- 放置footer插槽 -->
      <el-row type="flex" justify="end">
        <el-col :span="8">
          <el-button size="small" @click="cancleBtn">取消</el-button>
          <el-button size="small" type="primary" @click="okBtn">确定</el-button>
        </el-col>
      </el-row>
    </el-dialog>

    <el-dialog title="分配权限" :visible="showPerDialog" @close="perCancelBtn">
      <!-- 权限是树形结构 -->
      <!-- show-checkbox 可被选择 check-strictly 父子是否不关联 -->
      <!-- id作为唯一标识 -->
      <el-tree
        ref="permTree"
        :data="permData"
        :props="defaultProps"
        :show-checkbox="true"
        :check-strictly="true"
        :default-expand-all="true"
        :default-checked-keys="selectCheck"
        node-key="id"
      />
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="small" @click="perOkBtn">确定</el-button>
          <el-button size="small" @click="perCancelBtn">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getRoleList, getCompanyInfo, delRole, getRoleDetail, updateRole, addRole, assignPerm } from '@/api/setting'
import { getPermissionList } from '@/api/permission'
import { tranListToTree } from '@/utils'
import { mapGetters } from 'vuex'
export default {
  name: '',
  data() {
    return {
      list: [], // 承接数据
      page: {
        page: 1, // 当前所在页码
        pagesize: 10, // 每页显示数量
        total: 1 // 总页数
      }, // 页码信息
      formData: {}, // 承载公司信息
      showDialog: false, // 控制弹层显示（新增）
      showPerDialog: false, // 控制弹层显示（权限管理)
      roleForm: { name: '', description: '' },
      rules: { name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }] },
      permData: [], // 接受权限数据
      defaultProps: {
        label: 'name'
      }, // 定义显示字段的名称和子属性的字段名
      roleId: null, // 记录id
      selectCheck: []// 记录当前权限点的标识（默认显示）
    }
  },
  computed: {
    ...mapGetters(['companyId'])
  },
  created() {
    this.getRoleList()
    this.getCompanyInfo()
  },
  methods: {
    async getRoleList() {
      const { total, rows } = await getRoleList(this.page)
      this.page.total = total
      this.list = rows
    },
    changePage(newPage) {
      // newPage是当前点击的页码
      this.page.page = newPage
      // 获取点击页码的页面
      this.getRoleList()
    },
    async getCompanyInfo() {
      this.formData = await getCompanyInfo(this.companyId)
    },
    async delRole(id) {
      // 提示
      try {
        await this.$confirm('确认删除该员工吗？')
        // 点击了确定才可以执行下方
        await delRole(id)
        this.getCompanyInfo// 重新加载数据
        this.$message.success('成功删除该员工')
        this.getRoleList()
      } catch (err) {
        console.log(err)
      }
    },
    async editRole(id) {
      // 实现了数据的回写，将数据填充至弹层内方便在此基础上编辑
      this.roleForm = await getRoleDetail(id)
      this.showDialog = true
    },
    clearData() {
      // 清空数据函数
      this.roleForm = {
        name: '',
        description: ''
      }
      this.roleForm.id = ''
    },
    async okBtn() {
      // 校验函数除了用回调函数、还可以用promise的写法
      try {
        await this.$refs.roleForm.validate()
        //  校验通过才会执行下方内容
        // roleForm中有id就是编辑，没有id就是新增
        if (this.roleForm.id) {
          // 编辑
          await updateRole(this.roleForm)
        } else {
          // 新增
          await addRole(this.roleForm)
        }
        this.getRoleList()// 重新拉取数据
        this.$message.success('操作成功')
        // 关闭弹层
        this.showDialog = false// 关闭弹层会触发el-Dialog的close事件
      } catch (err) {
        console.log(err)
      }
    },
    cancleBtn() {
      this.clearData()
      this.showDialog = false
    },
    /**
     * 每次点击时获取权限点数据
     */
    async assignPerm(id) {
      this.roleId = id
      const { permIds } = await getRoleDetail(id)// 当前角色所拥有的权限的id
      this.selectCheck = permIds// 将当前角色所拥有的权限id赋值
      // 获取的所有权限点
      const res = await getPermissionList()
      this.permData = tranListToTree(res, '0')// 转化为树形结构
      this.showPerDialog = true
    },
    async perOkBtn() {
      // 提交权限
      await assignPerm({ permIds: this.$refs.permTree.getCheckedKeys(), id: this.roleId })// 利用这个参数获取到选中的树形结构
      this.$message.success('分配权限成功')
      this.showPerDialog = false
    },
    perCancelBtn() {
      this.showPerDialog = false
      this.selectCheck = []
    }
  }
}
</script>

<style>

</style>

